import { GlobalData } from "../Common/GlobalData";
import { IBagItemData, IGameData, IHospitalData, ISettingData, IStoreData, ITalkData, ITaskData, ITimeData } from "../Interface/IMessage";

export const GAME_DATA = "GAME_DATA";

export default class StorageUtil {
    private static _instance: StorageUtil = null;

    private storage: string = '';

    private version: string = 'v1.0.2';

    public static get instance() {
        if (this._instance === null) {
            this._instance = new this();
        }
        return this._instance;
    }

    protected constructor() {
        this.get();
    }

    private _sGameData: IGameData = null;
    public getGameData() {
        return this._sGameData;
    }
    public getTaskData() {
        return this._sGameData.taskData;
    }
    public getTalkData() {
        return this._sGameData.talkData;
    }
    public getHospitalData() {
        return this._sGameData.hospitalData;
    }
    public getBagData() {
        return this._sGameData.bagData;
    }
    public getStoreData() {
        return this._sGameData.storeData;
    }
    public getSettingData() {
        return this._sGameData.settingData;
    }
    public getTimeData() {
        if (!this._sGameData.timeData) {
            this._sGameData.timeData = this.defaultTimeData();
        }
        return this._sGameData.timeData;
    }

    public getDataByName<T extends keyof IGameData>(name: T) {
        if (!this._sGameData) {
            this._sGameData = this.get();
        }
        return this._sGameData[name];
    }

    public get(): IGameData {
        const key = this.getKey();
        this.storage = cc.sys.localStorage.getItem(key);
        if (this.storage === '') {
            this._sGameData = null;
        } else {
            this._sGameData = JSON.parse(this.storage);
        }
        if (!this._sGameData) {
            const defaultDatas: IGameData = {
                lastLoginTime: 0,
                isPlayMusic: 1,
                isPlaySound: 1,
                isShake: 1,
                money: 0,
                brain: 50,
                addPriceCount: 0,
                storeData: this.defaultStoreData(),
                talkData: this.defaultTalkData(),
                taskData: this.defaultTaskData(),
                // guideData: this.defaultGuideData(),
                bagData: this.defaultBagData(),
                hospitalData: this.defaultHospitalData(),
                settingData: this.defaultSettingData(),
                timeData: this.defaultTimeData(),
            }
            this._sGameData = defaultDatas;
            this.save();
        }

        // TODO 修改数据
        // for (let i = 10000; i < 10028; i++) {
        //     GlobalData.addBagData(i, 10);
        // }
        // this._sGameData.addPriceCount = 0;
        // this._sGameData.brain = 55;
        // this._sGameData.talkData.id = 10601;
        // this._sGameData.taskData.id = 5;
        // // this._sGameData.taskData.isAutoShow = 0;
        // // this._sGameData.hospitalData.student = 0;
        // this._sGameData.money = 5000000;
        // for (let i = 0; i < 1; i++) {
        //     // this._sGameData.bagData.push({ id: 10001, num: 1 });
        //     GlobalData.bagDatas.push({ id: 10001, num: 100 });
        // }

        // for (let i = 10016; i < 10028; i++) {
        //     GlobalData.addBagData(i, 100);
        // }
        // for (let i = 10011; i < 10015; i++) {
        //     GlobalData.addBagData(i, 100);
        // }

        this.resetSomeData();
        return this._sGameData;
    }

    public save<T extends keyof IGameData>(data: T = null) {
        // for (const data in this._sGameData) {
        //     console.log();
        // }

        const storage = JSON.stringify(this._sGameData);
        if (storage === this.storage) {
            console.log("数据一致~");
        } else {
            this.storage = storage;
            const key = this.getKey();
            cc.sys.localStorage.setItem(key, storage);
            console.log("StorageUtil.write()===>存数据:", storage);
        }
    }

    public clear() {
        cc.sys.localStorage.clear();
    }

    private getKey() {
        return `${GAME_DATA}_${this.version}`;
    }
    
    private defaultTaskData(): ITaskData {
        const taskData: ITaskData = { id: 1, isAutoShow: 0 };
        return taskData;
    }

    private defaultTalkData(): ITalkData {
        const talkData: ITalkData = { id: -1 };
        return talkData;
    }

    // private defaultGuideData(): IGuideData {
    //     const guideData: IGuideData = { isGuide: true, step: 0 };
    //     return guideData;
    // }

    private defaultBagData(): IBagItemData[] {
        const bagData: IBagItemData[] = [];
        return bagData;
    }

    private defaultStoreData(): IStoreData {
        const storeData: IStoreData = {
            stockMoney: 0,
            upItems: [],
            downItems: [],
        };
        return storeData;
    }

    private defaultHospitalData(): IHospitalData {
        const data: IHospitalData = {
            id: 1,
            groupLv: 1,
            cur: 0,
            exitTime: 0,
            autoEndTime: 0,
            student: 0,            // 拜师? 0.未拜师 1.已拜师 2.拒绝

            cellData: [],
            tempData: [],
            guestData: [],
            itemId: []
        };
        return data;
    }

    private defaultSettingData(): ISettingData[] {
        const datas: ISettingData[] = [];
        const config = GlobalData.getSetingIcons();
        config.forEach((o, i) => {
            const data: ISettingData = { id: i + 1, isUnlock: 0, isSelected: 0 };
            if (i === 0) {
                data.isUnlock = 1;
                data.isSelected = 1;
            }
            datas.push(data);
        });
        return datas;
    }

    public defaultTimeData(): ITimeData {
        return { day: 1, hour: 0, sceond: 0, timeScale: 5 };
    }

    /** 每天凌晨重置一些数据 */
    public resetSomeData() {
        // 时间相差一天  修改记录时间  刷新读取数据
        let year = new Date().getFullYear();
        let month = new Date().getMonth();
        let day = new Date().getDate();
        let todayTime = new Date(year, month, day).getTime();
        let recordTime: number = this._sGameData.lastLoginTime;
        if (todayTime - recordTime >= 1000 * 60 * 60 * 24) {
            // this._sGameData.todayPassCount = 0;
            // 修改记录时间戳
            this._sGameData.lastLoginTime = todayTime;
        }
    }
}